package com.bjsxt.commu4;

import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.*;

/**
 * 商品工厂类
 */
public class ProductFactory {

    //存储商品（增加、删除操作多，使用LinkedList效率更高）
    //List<String> productList = new LinkedList<>();

    BlockingQueue<String> productList = new LinkedBlockingQueue<>(10);
    int max = 10;

    public ProductFactory() {
    }

    /*public ProductFactory(int max) {
        this.max = max;
    }*/
    public ProductFactory(int max) {
        this.max = max;
        productList = new LinkedBlockingQueue<>(max);
    }

    //生产一件商品
    public void produce(String name) {

        //productList.add(name);      //抛出异常
        try {
            productList.put(name);      //阻塞
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        System.out.println(Thread.currentThread().getName() + "生产了：" + name
                + "，当前库存：" + productList.size());
    }

    //消费一件商品
    public void consume() {

        //String name = productList.remove();     //抛出异常
        String name = null;
        try {
            name = productList.take();      //阻塞
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        System.out.println(Thread.currentThread().getName() + "消费了：" + name
                + "，当前库存：" + productList.size());

    }

}
